import webview
import os
import json
import base64

# 定义全局变量
current_folder_path = ''

class API:
    # 选择文件夹
    def select_folder(self):
        global current_folder_path  # 声明使用全局变量
        folder_path = webview.windows[0].create_file_dialog(webview.FOLDER_DIALOG)
        if folder_path:
            current_folder_path = folder_path[0]
            print(f"选择的文件夹路径: {current_folder_path}")
        else:
            print("未选择文件夹")
        return current_folder_path
    # 列出文件夹内容
    def list_files_and_folders(self):
        if not current_folder_path:
            return json.dumps([])
        files_and_folders = list_files_and_folders(current_folder_path)
        print(f"文件夹内容: {json.dumps(files_and_folders)}")
        return json.dumps(files_and_folders)
    
    # 读取文件并将其转换为 Base64 字符串
    def base64_str_from_file(self, file_path):
        print(f"读取文件: {file_path}")
        try:
            with open(file_path, "rb") as file:
                file_content = file.read()
                base64_string = "data:image/jpeg;base64," + base64.b64encode(file_content).decode('utf-8')
                # print(f"文件内容: {base64_string}")
            return base64_string
        except Exception as e:
            raise Exception(f"读取文件或编码过程中发生错误: {e}")
# 列出文件夹内容
def list_files_and_folders(path):
    result = []
    for entry in os.scandir(path):
        entry_info = {
            'name': entry.name,
            'path': entry.path
        }
        if entry.is_dir(follow_symlinks=False):
            entry_info['children'] = list_files_and_folders(entry.path)
        result.append(entry_info)
    return result

def main():
    api = API()
    webview.create_window('记事本', 'http://localhost:5173', js_api=api)
    webview.start()

if __name__ == '__main__':
    main()